<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

$message = '';

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['user_id' ,'title', 'category_id', 'content'] as $value) {

        // 判断参数是否传递过来
        if (!isset($_POST[$value])) {
            throw new Exception(fieldMap($value) . '为必传项');
        }

        // 判断参数是否为空
        if (empty($_POST[$value])) {
            throw new Exception(fieldMap($value) . '不能为空');
        }
    };

    // 判断用户是否存在
    $sql = 'select * from users where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['user_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('用户不存在');
    }
    $userName = $res['username'];
    $userId = $res['id'];

    // 判断分类是否存在
    $sql = 'select * from categories where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_POST['category_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('分类不存在');
    }
    $categoryName = $res['name'];

    // 插入
    $sql = 'insert into articles (user_id ,username, title, content, category, category_id) values(? ,?, ?, ?, ?, ?)';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$userId ,$userName, $_POST['title'], $_POST['content'], $categoryName, $_POST['category_id']]);
    if ($stmt->rowCount() <= 0) {
        throw new Exception('发布文章失败');
    }

    myResponse('', 1, 200);
} catch (Exception $e) {
    $message = $e->getMessage();
    myResponse($message, 0, 200);
}